import { useState, useMemo, useImperativeHandle, forwardRef, useEffect } from 'react';
import { Form, message } from 'antd';
import { schemaMap } from '@inbiz/render';
import { useOperation, useWorkbench, getMessage } from '@inbiz/react';
import { getDesignerShowType } from '@inbiz/utils';
import CustomTabs from '../components/CustomTabs';
import Process from './Process';
import Field from '../components/Field';
import { getJumpRuleValue, setProLconStringToObject } from '../../utils';
import { getPageDetails } from '../../server';

const GlobalSettings = forwardRef((props: any, ref) => {
    const { processDefinition, customModeler, processData } = props;
    const [curTab, setCurTab] = useState('process');
    const [controlData, setControlData] = useState<any[]>([]);
    const [form] = Form.useForm();
    let workbench = null;
    let operation = null;
    if (getDesignerShowType() !== 3) {
        workbench = useWorkbench();
        const currentWorkspace = workbench?.activeWorkspace || workbench?.currentWorkspace;
        const currentWorkspaceId = currentWorkspace?.id;
        operation = useOperation(currentWorkspaceId);
    };

    const customTabsData = useMemo(() => {
        return [
            {
                value: 'process',
                label: '流程设置',
                disabled: false,
            },
            // {
            //     value: 'field',
            //     label: '字段权限',
            //     disabled: true,
            // },
        ]
    }, []);

    const formItems: any = useMemo(() => {
        return [
            {
                key: 'process',
                component: Process,
            },
            // {
            //     key: 'field',
            //     component: Field,
            // },
        ]
    }, []);

    const getControlData = async () => {
        try {
            let _data: any;
            if (processData?.formTypes == 2) {
                _data = schemaMap(operation.tree, true)?.map((item) => {
                    return {
                        value: item?.value,
                        label: getMessage(item.name),
                    };
                });
            } else {
                let results = await getPageDetails({ ismove: false, processKey: processData?.processKey });
                if (results.details?.schema) {
                    let data = schemaMap(results.details?.schema);
                    _data = data.map((item) => {
                        return {
                            value: item?.value,
                            label: getMessage(item.name),
                        };
                    });
                };
            }
            setControlData(_data);
        } catch (error: any) {
            message.error(error);
        };
    };

    useEffect(() => {
        getControlData();
    }, [processData, operation]);

    useEffect(() => {
        const _processDefinition = {
            ...processDefinition,
            processName: processDefinition?.processName || customModeler?.get('canvas')?.getRootElement()?.name,
            reachMsg: {
                ifPush: true,
                template: processDefinition?.tanTemplate || null,
            },
            candidateMsg: {
                ifPush: true,
                template: processDefinition?.tCandidateTemplate || null,
            },
            assignMsg: {
                ifPush: true,
                template: processDefinition?.tAssignTemplate || null,
            },
            returnMsg: {
                ifPush: true,
                template: processDefinition?.trnTemplate || null,
            },
            timeOutMsg: {
                ifPush: true,
                template: processDefinition?.ttonTemplate || null,
            },
            endMsg: {
                ifPush: true,
                template: processDefinition?.pcnTemplate || null,
            },
            urgingMsg: {
                ifPush: true,
                template: processDefinition?.reminderMailTemplate || null,
            },
            cancelMsg: {
                ifPush: true,
                template: processDefinition?.tCancelProcessTemplate || null,
            },
            jumpRule: getJumpRuleValue(processDefinition),
            proLcon: processDefinition?.proLcon ? setProLconStringToObject(processDefinition?.proLcon) : processData?.proLcon ? setProLconStringToObject(processData?.proLcon) : { type: 'icon-process-morentubiao', color: '#fc9637' },
        }
        form.setFieldsValue(_processDefinition);
    }, [processDefinition, customModeler]);

    useImperativeHandle(ref, () => ({
        form,
    }));

    return (
        <>
            <CustomTabs tabs={customTabsData} onChange={setCurTab} curTab={curTab} />
            <Form
                labelCol={{ span: 5 }}
                wrapperCol={{ span: 19 }}
                labelAlign='left'
                labelWrap={true}
                layout={'horizontal'}
                form={form}
            >
                {
                    formItems?.map((item: { component: any; key: string }) => {
                        return (
                            <div style={{ display: curTab == item.key ? 'block' : 'none' }}>
                                <item.component {...props} form={form} controlData={controlData}/>
                            </div>
                        )
                    })
                }
            </Form>
        </>
    );
});

export default GlobalSettings;